// 假设这里是原生fetch的封装，实际使用时可能需要替换为具体环境的请求库
async function req(url, options) {
    const fetchOptions = {
        method: options.method,
        headers: options.headers || {},
        timeout: options.timeout
    };

    if (options.method.toLowerCase() === 'post') {

        if (options.postType === 'form') {
            fetchOptions.body = new URLSearchParams(options.data).toString();
            fetchOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded'; //application/x-www-form-urlencoded
        }else if(options.postType === 'text'){
            fetchOptions.body = options.data;
            fetchOptions.headers['Content-Type'] = 'text/plain';
        }
        else {
            fetchOptions.body = JSON.stringify(options.data);
            fetchOptions.headers['Content-Type'] = 'application/json';
        }
    }
    // console.log(options);

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), options.timeout);

    try {
        const response = await fetch(url, {
            ...fetchOptions,
            signal: controller.signal
        });

        clearTimeout(timeoutId);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        if(options.buffer == 2){
            let res = await response.blob();
            let res2 = blobToBase64(res);
            return {
                content: res2
            };
        }else if(options.buffer == 1){
            let res = await response.blob();
            let res2 = blobToBase64(res);
            return {
                content: res2
            };
        }

        return {
            content: await response.text()
        };
    } catch (error) {
        console.log(options);
        console.log(error);
        clearTimeout(timeoutId);
        if (error.name === 'AbortError') {
            throw new Error('Request timed out');
        }
        throw error;
    }
}

function blobToBase64(blob) {
    return new Promise((resolve, reject) => {
        const chunks = [];
        const reader = blob.stream().getReader();
        function read() {
            reader.read().then(({ done, value }) => {
                if (done) {
                    const buffer = Buffer.concat(chunks);
                    resolve(buffer.toString('base64'));
                    return;
                }
                chunks.push(Buffer.from(value));
                read();
            }).catch(reject);
        }
        read();
    });
}

async function request(reqUrl, data, header, method) {
    let res = await req(reqUrl, {
        method: method || 'get',
        data: data || '',
        headers: header || {},
        postType: method === 'post' ? 'form' : '',
        timeout: 5000,
    });
    return res.content;
}

export { req, request };
// export default req;